package com.lzx.hbh_system.service.Impl;

import com.alibaba.fastjson.JSON;
import com.lzx.hbh_system.bo.dict.DictsProvince;
import com.lzx.hbh_system.mapper.DictsProvinceMapper;
import com.lzx.hbh_system.service.ProvinceService;
import com.lzx.hbh_system.util.RedisUtils;
import com.lzx.hbh_system.util.responseEntity.RespOutMsgHeader;
import com.lzx.hbh_system.util.responseEntity.ResponseView;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProvinceServiceImpl implements ProvinceService {
    @Autowired
    private DictsProvinceMapper dictsProvinceMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ModelMapper modelMapper;
    @Override
    public ResponseView getAll() {
        // 初始化返回视图
        ResponseView responseView = new ResponseView();
        List<Object> objects = redisUtils.getList("ProvinceList");
        List<DictsProvince> dictsProvinceList = new ArrayList<>();
        if(objects != null && objects.size() != 0){ //
            List<DictsProvince> finalProvinceList = new ArrayList<>(); // 转换完对象类型的省会对象存放集合
            objects.forEach(obj -> {
                DictsProvince province = JSON.parseObject(obj.toString(),DictsProvince.class);
                finalProvinceList.add(province);
            });
            dictsProvinceList.addAll(finalProvinceList);
        }else{ // redis 拿到的数据为空的情况下 才去数据库中拿数据
            dictsProvinceList = dictsProvinceMapper.queryAll();
            // 将拿到的数据存放至redis中
            redisUtils.lRightPushAll("ProvinceList",dictsProvinceList);
        }
        // 返回视图
        responseView.setMain(dictsProvinceList.toArray());
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success(dictsProvinceList.size(),true,"查询成功！"));
        return responseView;
    }
}
